#!/usr/bin/env python3
"""
响应管理器模块
专门处理移动端数据格式构建和各种类型的响应
"""

import time
from typing import Any, Optional

# 导入依赖
from speech_convert.models.response import ResponseCode
from speech_convert.models.speaker_info import SpeakerInfoData
from speech_convert.models.speech_recognition import SpeechRecognitionData
from speech_convert.server.response_builder import ResponseBuilder
from speech_convert.utils.speaker_manager import SpeakerManager


class ResponseManager:
    """响应管理器 - 专门处理移动端数据格式构建"""

    def __init__(self, speaker_manager: SpeakerManager):
        self.speaker_manager = speaker_manager

    def success(
        self,
        text: str,
        mode: str,
        status: str,
        wav_name: str,
        speaker_info: Optional[SpeakerInfoData] = None,
        confidence: float = 0.95,
        duration: int = 3000,
    ) -> SpeechRecognitionData:
        """创建语音识别响应"""
        current_time = int(time.time() * 1000)  # 毫秒时间戳

        # 使用 ResponseBuilder 创建标准化响应
        response = ResponseBuilder.success(
            message_id=self.speaker_manager.get_message_id(),
            timestamp=current_time,
            mode=mode,
            status=status,
            text=text,
            session_id=self.speaker_manager.get_session_id(),
            start_time=current_time - duration,
            end_time=current_time,
            duration=duration,
            confidence=confidence,
            speaker_info=speaker_info,
            message="语音识别成功",
        )
        return response

    def create_error_response(
        self, error_msg: str, error_code: str = "UNKNOWN_ERROR"
    ) -> Any:
        """创建错误响应"""
        # 根据错误代码映射到HTTP状态码
        code_mapping = {
            "UNKNOWN_ERROR": ResponseCode.INTERNAL_ERROR,
            "AUTH_ERROR": ResponseCode.UNAUTHORIZED,
            "ACCESS_DENIED": ResponseCode.FORBIDDEN,
            "NOT_FOUND": ResponseCode.NOT_FOUND,
            "BAD_REQUEST": ResponseCode.BAD_REQUEST,
        }
        response = ResponseBuilder.error(
            code=code_mapping[error_code], message=error_msg
        )

        return response

    def create_status_response(
        self, status: Optional[str] = None, data: Optional[dict[str, Any]] = None
    ) -> Any:
        """创建状态响应"""
        details = data or {}
        details["session_id"] = self.speaker_manager.get_session_id()

        response = ResponseBuilder.status(
            status=status, details=details, message=f"状态更新: {status}"
        )

        return response

    def create_connection_response(
        self, action: Optional[str] = None, client_info: Optional[dict[str, Any]] = None
    ) -> Any:
        """创建连接状态响应"""
        server_info = {
            "session_id": self.speaker_manager.get_session_id(),
            "timestamp": int(time.time() * 1000),
        }

        if client_info:
            server_info.update(client_info)

        supported_features = [
            "speech_recognition",
            "speaker_identification",
            "real_time_streaming",
            "multi_speaker_support",
        ]

        response = ResponseBuilder.connection(
            connection_id=self.speaker_manager.get_session_id(),
            server_info=server_info,
            supported_features=supported_features,
            message=f"连接状态: {action}",
        )

        return response

    def get_log_message(
        self, text: Optional[str], speaker_info: Optional[dict[str, Any]], mode: str, status: str
    ) -> str:
        """生成日志显示信息"""
        if speaker_info:
            speaker_name = speaker_info.get("name", "未知说话人")
            status_text = "最终" if status == "final" else "临时"
            return f'📤 发送识别结果 → 客户端: [{speaker_name}] "{text}" ({status_text}, 模式:{mode})'
        else:
            status_text = "最终" if status == "final" else "临时"
            return f'📤 发送识别结果 → 客户端: "{text}" ({status_text}, 模式:{mode})'

    def get_session_summary(self) -> dict[str, Any]:
        """获取会话摘要信息"""
        stats = self.speaker_manager.get_statistics()
        current_session = stats["current_session"]
        speakers = self.speaker_manager.get_session_speakers()

        speaker_list: list[dict[str, Any]] = []
        for speaker_id in speakers:
            speaker_info = self.speaker_manager.get_speaker_info(speaker_id)
            if speaker_info:
                speaker_list.append(
                    {
                        "id": speaker_info["speaker_id"],
                        "name": speaker_info["name"],
                        "color": speaker_info["color"],
                    }
                )

        return {
            "session_id": current_session,
            "duration": stats["session_duration"],
            "message_count": stats["message_count"],
            "speaker_count": len(speakers),
            "speakers": speaker_list,
        }
